import { TablePaginationConfig } from "@/components/base";
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";

/** 管理分页数据 */
export function usePagination() {

    const location = useLocation();
    const navigate = useNavigate();

    const setPagination = React.useCallback((pagination: TablePaginationConfig) => {
        const search = new URLSearchParams(window.location.search);
        search.set('page', `${pagination.current}`);
        search.set('pageSize', `${pagination.pageSize}`);
        navigate({
            pathname: location.pathname,
            search: search.toString()
        }, {
            state: { ...location.state }
        });
    }, [location.pathname, location.state, navigate]);

    const page = React.useMemo<number>(() => {
        return Number(new URLSearchParams(location.search).get('page')) || 1;
    }, [location.search]);

    const pageSize = React.useMemo<number>(() => {
        return Number(new URLSearchParams(location.search).get('pageSize')) || 10;
    }, [location.search]);

    return {
        setPagination,
        page,
        pageSize,
    }
}